package com._21cn._front.cms.page.pc;

import com._21cn._front.GenerateHandler;
import com._21cn.cms.common.obj.ResponseObj;
import com._21cn.cms.template.entity.Template;
import com._21cn.cms.template.service.TemplateService;
import com._21cn.cms.template.utils.TemplateHelper;
import com._21cn.cms.template.utils.label.ToolsLabel;
import com._21cn.cms.template.utils.label.YellowPageLabel;
import com._21cn.framework.http.HttpRequestInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Component("pcYellowPageList")
public class PcYellowPageList implements GenerateHandler {
    private static Integer templateId = 23;
    private static String templateContent = "";

    @Autowired
    private TemplateService templateService;

    @Autowired
    private YellowPageLabel yellowPageLabel;

    @Autowired
    private ToolsLabel toolsLabel;

    public ResponseObj generate(HttpServletRequest request) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        Integer pageNo = reqInfo.getIntParameter("pageNo", 1);
        Integer pageSize = reqInfo.getIntParameter("pageSize", 10);
        Integer areaId = reqInfo.getIntParameter("areaId", 0);
        Integer cateId = reqInfo.getIntParameter("cateId", 0);
        String keyword = reqInfo.getParameter("keyword", "");
        String currentUrl = reqInfo.getUrl();

        ResponseObj responseObj = new ResponseObj();
        try
        {
            Map maps = new HashMap();
            maps.put("yellowPageLabel", this.yellowPageLabel);
            maps.put("toolsLabel", this.toolsLabel);

            Template template = templateService.getById(templateId);
            templateContent = template.getContent();

            String templateStr = templateContent.replace("{pageNo}", pageNo.toString())
                    .replace("{pageSize}", pageSize
                            .toString())
                    .replace("{areaId}", areaId
                            .toString())
                    .replace("{cateId}", cateId
                            .toString())
                    .replace("{keyword}", keyword)
                    .replace("{currentUrl}", currentUrl);

            String content = TemplateHelper.evaluateTemplate(templateStr, new Map[] { maps });

            responseObj.setErrorCode(0);
            responseObj.setMessage(content);
        }
        catch (Exception e) {
            responseObj.setErrorCode(1);
            responseObj.setMessage("生成页面异常");
        }

        return responseObj;
    }
}